﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.Objects;
using Northwind.NET.Settings;
using Northwind.NET.Model;

namespace Northwind.NET.EDM.FE.WinForms.Controls
{
    public partial class OrdersUserControl : BaseUserControl
    {
        public OrdersUserControl()
        {
            InitializeComponent();
        }

        public override string FormCaption { get { return Settings.Resources.OrdersFormCaption; } }
        public override dynamic GetEntitySet(ObjectContext context)
        {
            return context.CreateObjectSet<Model.Order>();
        }

        public override BindingSource UserControlBindingSource { get { return orderBindingSource; } }

        internal override void SetBindingSource()
        {
            base.SetBindingSource();

            //setOrderDetailsDataSource();
            var dataSet = _context.CreateObjectSet<Order>().FirstOrDefault();
            if (dataSet == null)
            {
                customerOrdersProductsDataGridView.DataSource = _context.CreateObjectSet<Order>().FirstOrDefault();
            }
            else
            {
                setOrderDetailsDataSource(dataSet.ID.ToString());  
                setOrderTotals(dataSet.ID.ToString());
            }


            billToComboBox.DataSource = _context.CreateObjectSet<Model.Customer>(); 
            //billToComboBox.DisplayMember = "ContactName";
 
            var employees = (from e in _context.Employee
                             select new { e.ID, FullName = e.LastName + " " + e.FirstName });
            salesPersonComboBox.DataSource = employees; 
            //salesPersonComboBox.DisplayMember = "FullName";

            shipViaComboBox.DataSource  = _context.CreateObjectSet<Model.Shipper>(); 
            //shipViaComboBox.DisplayMember = "Name";

        }

        private void setOrderDetailsDataSource(string orderIdStr)
        {
            int orderId = -1;
            bool ret = Int32.TryParse(orderIdStr, out orderId);
            var result = from o in _context.OrderDetail
                         join p in _context.Product
                         on o.ProductID equals p.ID
                         where o.OrderID == orderId
                         select new
                         {
                             o.ID,
                             o.ProductID,
                             ProductName = p.Name,
                             o.UnitPrice,
                             o.Quantity,
                             o.Discount,
                             ExtendedPrice = (float?)o.UnitPrice * o.Quantity * (1 - o.Discount)
                         };

            customerOrdersProductsDataGridView.DataSource = result;
        }

        private void setOrderTotals(string orderIdStr)
        {
            int orderId = -1;
            bool ret = Int32.TryParse(orderIdStr, out orderId);

            var result1 = from orderDetail in _context.OrderDetail
                         join order in _context.Order
                         on orderDetail.OrderID equals order.ID
                         let freight = order.Freight 
                         where order.ID == orderId
                         group orderDetail by order.ID into g
                         select new
                         {
                             OrderId = g.Key,
                             ExtendedPrice = g.Sum(orderDetail=>(float?)orderDetail.UnitPrice * orderDetail.Quantity * (1 - orderDetail.Discount)),
                         };
            var result = (from row in result1
                         join order in _context.Order
                         on row.OrderId equals order.ID
                         select new
                         {
                             row.OrderId,
                             row.ExtendedPrice,
                             order.Freight,
                             TotalPrice = row.ExtendedPrice + (float?)order.Freight
                         }).FirstOrDefault() ;

            if (result != null)
            {
                totalExtendedPriceTextBox.Text = string.Format("{0:C2}",result.ExtendedPrice); 
                freightTextBox.Text = string.Format("{0:C2}",result.Freight);
                orderTotalTextBox.Text = string.Format("{0:C2}", result.TotalPrice);
            }
        }

        private void orderBindingSource_CurrentChanged(object sender, EventArgs e)
        {
            setOrderDetailsDataSource(txtOrderId.Text);
            setOrderTotals(txtOrderId.Text);
            setBillToValues();
        }

        private void billToComboBox_SelectedValueChanged(object sender, EventArgs e)
        {
            setBillToValues();
            setShipViaValues();
        }


        private void setBillToValues()
        {
            ComboBox comboBox = billToComboBox;
            if (comboBox.SelectedValue == null) return;

            int customerId = (int)comboBox.SelectedValue;

            //Northwind.NET.FE.Datasets.OrdersFormDataSet.CustomerRow customer =
            // this.ordersFormDataSet.Customer.FindByID(customerId);
            var customer = (from c in _context.Customer
                           where c.ID == customerId
                           select c).SingleOrDefault<Customer>();
            if (customer != null)
            {
                billToAddressTextBox.Text = customer.Address;
                billToRegionTextBox.Text = customer.Region;
                billToCityTextBox.Text = customer.City;
                billToPostalCodeTextBox.Text = customer.PostalCode;
                billToCountryTextBox.Text = customer.Country;
            }
        }
        private void setShipViaValues()
        {
            ComboBox comboBox = billToComboBox;
            if (comboBox.SelectedValue == null) return;

            int customerId = (int)comboBox.SelectedValue;

            //Northwind.NET.FE.Datasets.OrdersFormDataSet.CustomerRow customer =
            // this.ordersFormDataSet.Customer.FindByID(customerId);
            var customer = (from c in _context.Customer
                           where c.ID == customerId
                           select c).SingleOrDefault<Customer>();
            if (customer != null)
            {
                shipNameTextBox.Text = customer.Name;
                shipAddressTextBox.Text = customer.Address;
                shipRegionTextBox.Text = customer.Region;
                shipCityTextBox.Text = customer.City;
                shipPostalCodeTextBox.Text = customer.PostalCode;
                shipCountryTextBox.Text = customer.Country;
            }
        }

        //private InvoiceReport _report;
        private void printInvoiceButton_Click(object sender, EventArgs e)
        {
            //_report = new InvoiceReport();
            //_report.PreviewInvoice(Int32.Parse(iDTextBox.Text));
            todo();
        }

    }
}
